<template>
  <van-popup
    teleport="body"
    v-model:show="show"
    closeable
    position="right"
    :style="{ height: '100%', width: '100%' }"
  >
    <div class="content_wrapper main_bg">
      <headback
        :title="t('修改挂单')"
        isGoBack
        :goBack="goBack"
        class="border_bottom"
      ></headback>
      <div class="wrap">
        <div class="lend_des">
            {{ orderItem.orderType==1 ? '卖出挂单': '买入挂单' }}
        </div>
        <div class="form_box">
     
        <div class="form_line">
          <div class="lend_title">
            {{ t("allAmount") }}
          </div>
          <div class="interest_amount">
            <div  class="interest_amount" v-if="orderItem.orderType=='2'">
            <img class="token_img" :src="requireImg(store.state.usdtImg)" alt="" />
            <span class="amount_value2"> {{ orderItem.allAmount }}</span> {{ store.state.USDT}}
           </div>
          <div class="interest_amount" v-else>
            <img class="token_img"  :src="requireImg(store.state.btcImg)" alt="" />
           <span class="amount_value2">{{ orderItem.allAmount }} </span>  
            {{ store.state.BTC}}
          </div>
          </div>
        </div>
        <div class="form_line"> 
          <div class="lend_title">
            {{ t("saveAmount") }}
          </div>
          <div class="interest_amount">
            <div  class="interest_amount" v-if="orderItem.orderType=='2'">
            <img class="token_img" :src="requireImg(store.state.usdtImg)" alt="" />
            <span class="amount_value2"> {{ orderItem.amount }}</span> {{ store.state.USDT}}
           </div>
          <div class="interest_amount" v-else>
            <img class="token_img"  :src="requireImg(store.state.btcImg)" alt="" />
           <span class="amount_value2">{{ orderItem.amount }} </span>  
            {{ store.state.BTC}}
          </div>
          </div>
          
        </div>
        <div class="form_line">
          <div class="lend_title">{{  '价格设置' }}</div>
          :
          <van-radio-group  v-model="priceType" shape="square"  direction="horizontal">
            <van-radio name="1">
              <div class="flex_class">
              {{ '固定价格' }}  
              <iconTip title="" placement="top">
                <div>买入VDS价格固定，接单者以订单设置的价格为准</div>
              </iconTip>
            </div>
            </van-radio>
            <van-radio name="2">
              <div class="flex_class">
              {{ t('实时价格') }}
              <iconTip title="" placement="top-end">
                <div>买入VDS价格，由接单时的实时价格决定</div>
              </iconTip>
            </div>
            </van-radio>
          </van-radio-group>
        </div>
        <div class="price_box tip">当前实时价格  1 {{ store.state.BTC }} ≈ {{ store.state.tokenPrice }} {{ store.state.USDT }}</div>
                  <!-- 固定价格设置 -->
        <div class="form_line" v-if="priceType==1">
          <div class="lend_title">
            {{ t("固定价格") }}
          </div>:
          <div class="flex_box"> 
            <div class="form_item">
              <div class="form_content">
            <van-field class="rate_class" type="number" v-model="fixedPrice" :placeholder="t('')">
              <template #button> U </template>
            </van-field>
            </div>
            <iconTip title="" placement="top-end">
              <div>交易价格以固定设置的价格为准</div>
            </iconTip>
            </div>
          </div>
        </div>
        <!-- 实时价格 -->
        <div class="form_line" v-if="priceType==2">
          <div class="lend_title">
            {{ t("价格浮动") }}
          </div>:
          <div class="flex_box"> 
            <div class="form_item">
              <div class="form_content">
            <step v-model="upDown" ></step>
            </div>
            <iconTip title="" placement="top">
              <div>设置买入价格跟当时实时价格的浮动比例</div>
              <div> 为了尽快买入，建议设置上浮比例 </div>
            </iconTip>
            <div class="price_box"> ≈ {{ upDownValue }} {{ store.state.USDT }}</div>
            
            </div>
          </div>
        </div>
        
        <div class="form_line">
        <div class="lend_title">
          {{ t("有效期") }}
        </div>:
        <div class="form_item">
              <div class="form_content">
                <van-field type="digit"  class="rate_class" v-model="customDay" :placeholder="t('')">
              <template #button> </template>
          </van-field>
            <span class="rate_margin">days    <iconTip title="" placement="top-end">
                <div>超过有效期订单会被隐藏</div>
              </iconTip></span> 
            </div>
            </div>
          
        </div>
    
        <!-- 小费 -->
        <div class="form_line">
          <div class="lend_title">
            {{ t("ConfirmationTip") }}
          </div>:
          <div class="flex_box"> 
            <div class="form_item">
              <div class="form_content">
            {{  parseFloat((orderItem.tip *100).toFixed(4)) }} %
            <span class="rate_margin">
              <div class="interest_amount">
                  <span>{{ tipValue }}</span> 
                  <div  class="interest_amount" v-if="orderItem.orderType=='2'">
            <img class="token_img" :src="requireImg(store.state.usdtImg)" alt="" />
           </div>
           <div class="interest_amount" v-else>
            <img class="token_img"  :src="requireImg(store.state.btcImg)" alt="" />
            {{ store.state.BTC}}
          </div>
                </div>
            </span> 
            <iconTip title="" placement="top-end">
              <div>小费比例大于等于平台或交易员</div>
                <div>小费给到交易员</div>
                <div>如果没有选择交易员</div>
                <div>则给到平台</div>
              </iconTip>
            </div>
            </div>
          </div>
        </div>
 
          <div class="form_item form_line" style="flex: 1">
            <div class="lend_title">{{ t("shop") }}</div>
            :
            <div class="form_content">
              <van-cell class="tarder_name" @click="setShop" :value="props.shopData.name||shopName" :is-link="!props.shopData.name" />
            </div>
          </div>
        <div class="form_line">
          <div class="lend_title">
            {{ t("remark") }}
          </div>:
          <div class="flex_box" style="width: 100%;"> 
            <div class="form_item">
              <div class="form_content textArea_field">
            <van-field  type="textarea" rows="1"  v-model="formData.remark" :placeholder="t('')">
            </van-field>
            </div>
            </div>
          </div>
        </div>
      </div>
      </div>
      <div class="fixedbutton background_box">
        <van-button :loading="loading" @click="confirm" type="primary">
          <div>{{ t("confirm") }}</div>
        </van-button>
      </div>
    </div>
  </van-popup>
  <shopChoose
    v-model="showShop"
    v-model:checkedValue="shopId"
    @change="shopChange"
  ></shopChoose>
</template>
<script setup>
import AESUtils from "@/utils/AES.js";
import { showToast } from "vant";
import "vant/es/toast/style";
import { ethers } from "ethers";
import { useStore } from "vuex";
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useI18n } from "vue-i18n";
const { locale, t } = useI18n();
import { usdtContract, usdcContract, c2cContract } from "@/utils/config.js";
const store = useStore();
import { useRouter } from "vue-router";
import { upload, jsonUpload, IPFS_PUBLIC_URL, getJson } from "@/api/User.js";
import c2cEth from "@/utils/c2cEth.js";
import eth from "@/utils/eth.js";
const requireImg = (imgPath) => {
  return new URL(`../assets/images/${imgPath}`, import.meta.url).href;
};
const showPopover2 = ref(false);
const priceType = ref('1')
const usdtValue = ref(10);
const router = useRouter();
const loading = ref(false);
const fixedPrice = ref(0)
const customDay = ref(30)
const showShop = ref(false);
const shopName = ref("");
const tipRate = ref(0)
const shopId = ref("");
const setShop = () => {
  if(props.shopData.name){

  }else{
    showShop.value = true;
  }
};
const nowShop = ref({})
const shopChange = (item) => {
  shopId.value = item.account;
  shopName.value = item.name;
  nowShop.value = item
  tipRate.value = item.tipRate*10000/100
};
const tokenList = [
  {
    contract: usdtContract[0],
    name: usdtContract[1],
    decimal: usdcContract[3],
    img: usdtContract[4],
  },
];
const nowToken = ref(tokenList[0]);
const upDown = ref(0)
const upDownValue = computed(()=>{
  return parseFloat((store.state.tokenPrice*(1+(upDown.value/100))).toFixed(4)) 
})
const realRate = ref(1)

const tipValue = computed(()=>{
  return  parseFloat(((props.orderItem.tip) * props.orderItem.allAmount).toFixed(6))
})
// 手续费
const feeValue = computed(()=>{
  return  parseFloat(((store.state.platformFee) * usdtValue.value).toFixed(6))
})

const props = defineProps({
  shopData:{
    type:Object,
    default:()=>{
      return {}
    }
  },
  modelValue: {
    type: Boolean,
    default: false,
  },
  orderItem: {
    type: [Object, Array],
    default: {},
  },
});
shopName.value = props.shopData.name
const emit = defineEmits(["change", "update:modelValue", "close"]);
let show = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});
watch(
  () => show.value,
  (newValue) => {
    if (newValue) {
      main();
    }
  }
);
const goBack = () => {
  show.value = false;
};
let formData = ref({
  id: "1",
  price: "",
  remark: "",
});
const main = async () => {
};
main();
const goToPage = (value) => {
  router.push({
    name: value,
  });
};
const confirm = async () => {
  if (!usdtValue.value) {
    showToast(t("pleseAmount"));
    return;
  }
  if (priceType.value==1&&fixedPrice.value<=0) {
    showToast(t("请输入正确的价格"));
    return;
  }
  if (usdtValue.value < 10) {
    showToast(t("minAmount"));
    return;
  }
  if(tipRate.value < store.state.minFee*100){
    showToast("小费不能低于" + (store.state.minFee*10000/100) + '%')
    return
  }
  if(tipRate.value < nowShop.value.tipRate*100){
    showToast("小费不能低于" + (nowShop.value.tipRate*10000/100) + '%')
    return
  }
  let tokenValue = await eth.getBalanceOf(
    nowToken.value.contract,
    nowToken.value.decimal
  );
  let needPayU = parseFloat(((Number(usdtValue.value) + Number(tipValue.value) +   Number(feeValue.value)) * 1.1).toFixed(6));
  if (tokenValue < needPayU )  {
    showToast(t("noMoney"));
    return;
  }
  loading.value = true;
  try {
    let allowance = await eth.getAllowance(
      nowToken.value.contract,
      c2cContract,
      nowToken.value.decimal
    );
    if (needPayU > Number(allowance)) {
      await eth.approve(
        needPayU,
        nowToken.value.contract,
        c2cContract,
        nowToken.value.decimal
      );
      // 授权
    }
    let amount = ethers.utils.parseUnits(
      String(usdtValue.value),
      nowToken.value.decimal
    );
    let hex = await c2cEth.ContractWithSinger.createOrder(
      amount,
      2,
      customDay.value,
      priceType.value,
      ethers.utils.parseUnits(fixedPrice.value,usdtContract[3]),
      upDown.value>=0?'1':'2', //正负
      (Math.abs(upDown.value)/100*10000).toFixed(0),   //上浮比例
      (tipRate.value/100*10000).toFixed(0), 
      shopId.value || "0x0000000000000000000000000000000000000000",
      formData.value.remark,
    );
    await hex.wait();
    loading.value = false;
    showToast(t("orderSuccess"));
    goBack()
    goToPage("myC2C");
  } catch (err) {
    showToast(t("orderFail"));
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.form_box{
  border: 1px solid #888;
  margin-top: 8px;
  padding: 2px 6px 12px 6px;
  border-radius: 8px;
}
.flex_class{
  display: flex;
  align-items: center;
}
.tip{
  color: #f77a2f;
}
.tip2{
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 6px;
  .num_value{
    font-size: 14px;
    font-weight: bold;
    color: #f77a2f;
  }
}
:deep .van-cell__right-icon {
  display: flex;
  align-items: center;
}
.rate_margin{
  margin-left: 10px;
  display: flex;
  align-items: center;
}
.form_line {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 10px;
  min-height: 32px;
  // font-size: 11px;
}
.language_box {
  padding: 5px 0px;
  background: #222143;
}
.menu_box {
  min-width: 148px;
  max-height: 75vh;
  overflow: auto;
  background-color: #222143;
  border-radius: 8px;
  padding: 8px;
  box-shadow: rgba(0, 0, 0, 0.25) 0 4px 12px;
  // font-size: 14px;
  z-index: 100;
}
.days_rate{
  margin-left: 10px;
  color: #999;
}
.menu_item {
  display: flex;
  padding: 8px;
  color: inherit;
  text-decoration: none;
  font-weight: 400;
}
:deep .van-popover__wrapper{
  flex-shrink: 0;
}
.color_light2 {
  box-sizing: border-box;
  color: #ddd;
  display: inline-block;
  border: 1px solid #414c60;
  padding: var(--van-cell-vertical-padding) 6px;
  height: 1.2rem;
  // margin-left: 10px;
  
  border-radius: 5px;
  flex-shrink: 0;
  min-width: auto;
  display: flex;
  align-items: center;
  .icon_down {
    font-size: 10px;
    margin-left: 4px;
  }
  img {
    height: 16px;
    margin-right: 7px;
  }
}
.color_light {
  color: #ddd;
  display: inline-block;
  border: 1px solid #414c60;
  padding: var(--van-cell-vertical-padding) 6px;
  margin-left: 10px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  .icon_down {
    font-size: 10px;
    margin-left: 4px;
  }
  img {
    height: 16px;
    margin-right: 7px;
  }
}
.usdt_box {
  color: #ddd;
  display: inline-block;
  border-radius: 5px;
  display: flex;
  align-items: center;
  img {
    height: 16px;
    margin-right: 7px;
  }
}
.language_item {
  // font-size: 12px;
  padding: 10px 15px;
  cursor: pointer;
  text-align: center;
  display: flex;
  align-items: center;

  .van-image {
    height: 18px;
    width: 18px;
    margin-right: 8px;
  }
}
.language_item2 {
  padding: 6px 15px;
  cursor: pointer;
  text-align: center;
  display: flex;
  align-items: center;
}
.confirm_notice {
  color: #333;
}
.drop_item {
  padding: 10px 10px;
  display: flex;
  align-items: center;
  gap: 8px;
  .drop_num {
    width: 20px;
    text-align: right;
  }
}
.drop_active {
  color: #f77a2f;
}
.interest_amount {
  display: flex;
  align-items: center;
  gap: 6px;
}
// .van-dropdown-menu{
//    border: 1px solid #414c60;
//   border-radius: 8px;

// }
:deep .van-dropdown-menu__title {
  font-size: 12px;
}
:deep .van-dropdown-menu__bar {
  border: 1px solid #414c60;
  border-radius: 6px;
  height: 36px;
  display: inline-flex;
  padding-right: 10px;
  font-size: 10px;
}


.lend_title {
  font-weight: bold;
  min-width: 55px;
  text-align-last: justify;
  // font-size: 10px;
}
.lend_title2 {
  font-weight: bold;
  display: flex;
  align-items: center;
  min-width: 55px;
  margin: 10px 0;
  // font-size: 10px;
  gap: 6px;
}
.van-cell {
  // font-size: 12px;
  background: transparent !important;
}
.content_wrapper {
  height: calc(100vh - 10px);
  box-sizing: border-box;
  overflow: auto;
  background: #eff0f4;
}
.isHeight {
  height: 100vh;
}
.wrap {
  padding: 10px 12px 20px 12px;
  // min-height: calc(100vh - 150px);
  // overflow: auto;
  margin-top: 40px;
  position: relative;
  .lend_des {
    display: flex;
    line-height: 2em;
    font-size: 10px;
  }
  .van-button {
    margin-top: 0.58667rem;
    width: 100%;
    height: 1.06667rem;
    font-size: 0.48rem;
    font-weight: 500;
    border-radius: 0.53333rem;
  }

  .van-button--primary {
    border: none;
    font-size: 0.48rem;
    font-weight: 400;
  }

  :deep .van-cell__right-icon {
    font-size: 12px;
  }
  .picture_tips {
    color: #999;
  }

  .form_item {
    display: flex;
    padding: 0;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .form_title {
      display: flex;
      align-items: center;
      opacity: 0.8;
      // font-size: 11px;
    }

    .line_h30 {
      line-height: 30px;
    }
    .rate_class{
      width: 80px;
    }
    .form_content {
      flex: 1;
      display: flex;
      align-items: center;
      .van-field {
        border: 1px solid #414c60;
      }

      .radio_group {
        padding: 0.31rem 0.5rem;
      }
      .van-cell {
        // font-size: 11px;
      }
      // display: flex;
      // justify-content: flex-end;
    }
  }
}
</style>
